package com.example.memo2.utils

import android.content.Context
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.provider.MediaStore
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*

object MediaUtils {
    
    private const val IMAGES_DIR = "images"
    private const val AUDIO_DIR = "audio"
    
    /**
     * 获取应用内部图片存储目录
     */
    fun getImagesDir(context: Context): File {
        val dir = File(context.filesDir, IMAGES_DIR)
        if (!dir.exists()) {
            dir.mkdirs()
        }
        return dir
    }
    
    /**
     * 获取应用内部音频存储目录
     */
    fun getAudioDir(context: Context): File {
        val dir = File(context.filesDir, AUDIO_DIR)
        if (!dir.exists()) {
            dir.mkdirs()
        }
        return dir
    }
    
    /**
     * 从URI复制图片到应用内部存储
     */
    fun copyImageFromUri(context: Context, uri: Uri): String? {
        return try {
            val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
            
            // 获取文件扩展名
            val mimeType = context.contentResolver.getType(uri)
            val extension = when {
                mimeType?.contains("jpeg") == true || mimeType?.contains("jpg") == true -> "jpg"
                mimeType?.contains("png") == true -> "png"
                mimeType?.contains("webp") == true -> "webp"
                else -> "jpg" // 默认使用jpg
            }
            
            val fileName = "IMG_${timeStamp}.${extension}"
            val destinationFile = File(getImagesDir(context), fileName)
            
            println("正在复制图片: $uri 到 ${destinationFile.absolutePath}")
            
            context.contentResolver.openInputStream(uri)?.use { inputStream ->
                FileOutputStream(destinationFile).use { outputStream ->
                    val bytesCoiled = inputStream.copyTo(outputStream)
                    println("图片复制完成，大小: $bytesCoiled bytes")
                }
            }
            
            println("图片保存成功: ${destinationFile.absolutePath}")
            println("文件是否存在: ${destinationFile.exists()}")
            println("文件大小: ${destinationFile.length()} bytes")
            
            destinationFile.absolutePath
        } catch (e: IOException) {
            println("图片保存失败: ${e.message}")
            e.printStackTrace()
            null
        }
    }
    
    /**
     * 生成音频文件路径
     */
    fun generateAudioFilePath(context: Context): String {
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val fileName = "AUDIO_${timeStamp}.m4a"
        return File(getAudioDir(context), fileName).absolutePath
    }
    
    /**
     * 获取音频文件时长
     */
    fun getAudioDuration(filePath: String): Long {
        return try {
            val retriever = MediaMetadataRetriever()
            retriever.setDataSource(filePath)
            val duration = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
            retriever.release()
            duration?.toLongOrNull() ?: 0L
        } catch (e: Exception) {
            e.printStackTrace()
            0L
        }
    }
    
    /**
     * 格式化音频时长显示
     */
    fun formatDuration(durationMs: Long): String {
        val seconds = durationMs / 1000
        val minutes = seconds / 60
        val remainingSeconds = seconds % 60
        return String.format("%02d:%02d", minutes, remainingSeconds)
    }
    
    /**
     * 删除文件
     */
    fun deleteFile(filePath: String): Boolean {
        return try {
            val file = File(filePath)
            file.delete()
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }
    
    /**
     * 获取文件名
     */
    fun getFileName(filePath: String): String {
        return File(filePath).name
    }
    
    /**
     * 解析图片路径字符串（逗号分隔）
     */
    fun parseImagePaths(imagePathsString: String?): List<String> {
        return if (imagePathsString.isNullOrBlank()) {
            emptyList()
        } else {
            imagePathsString.split(",").filter { it.isNotBlank() }
        }
    }
    
    /**
     * 将图片路径列表转为字符串（逗号分隔）
     */
    fun joinImagePaths(imagePaths: List<String>): String? {
        return if (imagePaths.isEmpty()) {
            null
        } else {
            imagePaths.joinToString(",")
        }
    }
} 